﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Threading.Tasks;

namespace S4Project
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class AuthenticationMiddleware
    {
        private readonly RequestDelegate _next;

        public AuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, Func<Task> next)
        {
            // 检查请求头中是否有Authorization字段
            if (!context.Request.Headers.TryGetValue("Authorization", out var authValue))
            {
                context.Response.StatusCode = 401;
                return;
            }
            var token = authValue.ToString().Split(' ').Last();
            // 验证Token是否有效
            if (!IsValidToken(token))
            {
                context.Response.StatusCode = 401;
                return;
            }
            await next();
        }
        private bool IsValidToken(string token)
        {
            try
            {
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("kehanshizhizhu0104zyxkhshizhizhu")); // 请确保这与生成JWT时使用的密钥相同
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = securityKey,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero // 可以调整时钟偏差
                };

                var tokenValidator = new JwtSecurityTokenHandler();
                var principal = tokenValidator.ValidateToken(token, validationParameters, out var securityToken);

                return principal != null && securityToken is JwtSecurityToken jwtToken && !string.IsNullOrEmpty(jwtToken.RawData);
            }
            catch
            {
                return false;
            }
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class AuthenticationMiddlewareExtensions
    {
        public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AuthenticationMiddleware>();
        }
    }
}
